﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Learning
{
    public class LearningProvisioningEngine : SPWebProvisioningProvider
    {
        public override void Provision(SPWebProvisioningProperties props)
        {
            var web = props.Web;
            var lang = web.Language;
                
            web.ApplyWebTemplate("Learning#0");
            EnsureContentTypes(web, PublishingWeb.GetPagesListName(web));
            web.Webs.Add("raamatud", "Raamatud", "Raamatud", lang, "Learning#4", false, false);
            web.Webs.Add("ajakirjad", "Ajakirjad", "Ajakirjad", lang, "Learning#2", false, false);
            web.Webs.Add("veebistuudium", "Veebistuudium", "Veebistuudium", lang, "Learning#3", false, false);
            web.Update();
        }

        private static void EnsureContentTypes(SPWeb site, string pagesListName)
        {
            var pageCTs = site.Lists[pagesListName].ContentTypes;
            foreach (SPContentType contentType in site.Site.RootWeb.AvailableContentTypes)
            {
                if (IsCustomContentType(contentType) && pageCTs[contentType.Name] == null)
                    pageCTs.Add(contentType);
            }
        }

        ///<summary> 
        /// Determines whether a given content type is a custom type for this Feature.
        ///</summary> 
        private static bool IsCustomContentType(SPContentType contentType)
        {
            if (contentType.Hidden) return false;
            if (contentType.Group.ToUpper() != "Eneta") return false;
            return true;
        }
    }
}
